//
//  DebugH5WebViewController.m
//  YK_DebugManager
//
//  Created by edward on 2021/6/1.
//

#import "DebugH5WebViewController.h"
#import <WebKit/WebKit.h>

#pragma mark -------listView-------
@interface DebugH5webListView : UIView<UITableViewDelegate,UITableViewDataSource>
/***/
@property (nonatomic, strong) NSMutableArray *listArray;
///
@property(nonatomic,strong) UITableView *tableView;
///
@property(nonatomic,copy) void(^clickUrl)(NSIndexPath *indexPath,NSString *url);
///
@property(nonatomic,copy) void(^dissMissBlock)(void);

- (void)addListObject:(NSString *)url;

@end

@implementation DebugH5webListView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setupUI];
    }
    return self;
}

- (void)setupUI
{
    [self addSubview:self.tableView];
//    UISwipeGestureRecognizer *swip = [[UISwipeGestureRecognizer alloc]init];
//    swip.direction = UISwipeGestureRecognizerDirectionRight;
//    [swip addTarget:self action:@selector(dissMiss)];
//    [self addGestureRecognizer:swip];
}

- (void)addListObject:(NSString *)url
{
    [self.listArray insertObject:url atIndex:0];
    [self.tableView reloadData];
}

- (void)dissMiss
{
    if (self.dissMissBlock) {
        self.dissMissBlock();
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.listArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(UITableViewCell.class) forIndexPath:indexPath];
    cell.textLabel.text = self.listArray[indexPath.row];
    cell.backgroundColor = UIColor.clearColor;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.clickUrl) {
        self.clickUrl(indexPath, self.listArray[indexPath.row]);
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, 44)];
    
    UIButton *clearButton = [UIButton buttonWithType:UIButtonTypeCustom];
    clearButton.frame = CGRectMake(0, 0, self.bounds.size.width/2, 44);
    [clearButton setTitle:@"清除" forState:UIControlStateNormal];
    [clearButton setTitleColor:UIColor.redColor forState:UIControlStateNormal];
    clearButton.backgroundColor = UIColor.whiteColor;
    clearButton.tag = 060200;
    [clearButton addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *disMissButton = [UIButton buttonWithType:UIButtonTypeCustom];
    disMissButton.frame = CGRectMake(self.bounds.size.width/2, 0, self.bounds.size.width/2, 44);
    [disMissButton setTitle:@"关闭" forState:UIControlStateNormal];
    [disMissButton setTitleColor:UIColor.redColor forState:UIControlStateNormal];
    disMissButton.backgroundColor = UIColor.whiteColor;
    disMissButton.tag = 060201;
    [disMissButton addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [titleView addSubview:clearButton];
    [titleView addSubview:disMissButton];
    return titleView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 44;
}

- (UITableView *)tableView
{
    if(!_tableView)
    {
        UITableView *tableView = [[UITableView alloc]initWithFrame:self.bounds style:UITableViewStylePlain];
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.estimatedRowHeight = 85;
        tableView.rowHeight = UITableViewAutomaticDimension;
        tableView.backgroundColor = [UIColor.lightGrayColor colorWithAlphaComponent:0.3];
        [tableView registerClass:UITableViewCell.class forCellReuseIdentifier:NSStringFromClass(UITableViewCell.class)];
        _tableView = tableView;
    }
    return _tableView;
}

- (NSMutableArray *)listArray
{
    if (!_listArray) {
        _listArray = [NSMutableArray array];
    }
    return _listArray;
}

- (void)buttonClick:(UIButton *)button
{
    if (button.tag == 060200) {
        [self.listArray removeAllObjects];
        [self.tableView reloadData];
    }else if (button.tag == 060201){
        if (self.dissMissBlock) {
            self.dissMissBlock();
        }
    }else{
        return;
    }
}

@end

#pragma mark -------mainViewController-------
@interface DebugH5WebViewController ()<WKUIDelegate,UITextFieldDelegate,UIScrollViewDelegate>
/***/
@property (nonatomic,copy) NSString * h5Url;
/***/
@property (nonatomic, strong) UIProgressView * progressView;
/***/
@property (nonatomic, strong) UITextField * textField;
/***/
@property (nonatomic, strong) UIButton * goBackButton;
/***/
@property (nonatomic, strong) UIButton * gotoButton;
/***/
@property (nonatomic, strong) WKWebView * webView;
/***/
@property (nonatomic, strong) DebugH5webListView * listView;
///
@property(nonatomic,assign) BOOL isShowList;

@end

@implementation DebugH5WebViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"内置浏览器";
    [self.view addSubview:self.progressView];
    [self.view addSubview:self.goBackButton];
    [self.view addSubview:self.textField];
    [self.view addSubview:self.gotoButton];
    [self.view addSubview:self.webView];
    [self.view addSubview:self.listView];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemBookmarks target:self action:@selector(showListView)];
    
    // 监听加载进度
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)dealloc {
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    // 加载进度条
    if ([@"estimatedProgress" isEqualToString:keyPath]) {
        self.progressView.alpha = 1.0;
        NSLog(@"loding Progress: %lf", self.webView.estimatedProgress);
        
        [self.progressView setProgress:self.webView.estimatedProgress animated:YES];
        
        if (self.webView.estimatedProgress >= 1.0) {
            [UIView animateWithDuration:0.3f delay:0.1f options:UIViewAnimationOptionCurveEaseOut animations:^{
                self.progressView.alpha = 0;
            } completion:^(BOOL finished) {
                [self.progressView setProgress:0.0 animated:NO];
            }];
        }
    }
}


- (UIProgressView *)progressView
{
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, debug_top_Height, UIScreen.mainScreen.bounds.size.width, 3)];
        _progressView.tintColor = [UIColor blueColor];      // 进度条颜色
        _progressView.trackTintColor = [UIColor whiteColor];    // 进度条背景色
//        [_progressView setHidden:YES];
    }
    return _progressView;
}

- (UITextField *)textField
{
    if (!_textField) {
        _textField = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.goBackButton.frame) + 2, CGRectGetMaxY(self.progressView.frame), UIScreen.mainScreen.bounds.size.width - 120, 30)];
        _textField.placeholder = @"请输入链接";
        _textField.layer.borderWidth = 1;
        _textField.delegate = self;
        [_textField drawTextInRect:CGRectMake(10, 5, _textField.bounds.size.width - 20, _textField.bounds.size.height - 10)];
        _textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _textField.layer.borderColor = UIColor.lightGrayColor.CGColor;
        _textField.layer.cornerRadius = 8;
        _textField.clipsToBounds = YES;
    }
    return _textField;
}

- (UIButton *)goBackButton
{
    if (!_goBackButton) {
        _goBackButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _goBackButton.frame = CGRectMake(8, CGRectGetMaxY(self.progressView.frame), 50, 30);
        [_goBackButton setTitle:@"返回" forState:UIControlStateNormal];
        [_goBackButton setBackgroundColor:UIColor.blueColor];
        [_goBackButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        _goBackButton.layer.cornerRadius = 8;
        _goBackButton.clipsToBounds = YES;
//        _goBackButton.userInteractionEnabled = self.webView.canGoBack;
        [_goBackButton addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _goBackButton;
}

- (UIButton *)gotoButton
{
    if (!_gotoButton) {
        _gotoButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _gotoButton.frame = CGRectMake(CGRectGetMaxX(self.textField.frame)+2, CGRectGetMaxY(self.progressView.frame), 50, 30);
        [_gotoButton setTitle:@"前往" forState:UIControlStateNormal];
        [_gotoButton setBackgroundColor:UIColor.blueColor];
        [_gotoButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        _gotoButton.layer.cornerRadius = 8;
        _gotoButton.clipsToBounds = YES;
        [_gotoButton addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _gotoButton;
}

- (WKWebView *)webView
{
    if (!_webView) {
        _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.textField.frame), debug_screenW, debug_screenH - CGRectGetMaxY(self.textField.frame) - debug_bottom_safe)];
        _webView.UIDelegate = self;
        _webView.scrollView.delegate = self;
        _webView.allowsBackForwardNavigationGestures = NO;
    }
    return _webView;
}

- (void)buttonClick:(id)sender
{
    if (sender == self.goBackButton) {
        [self.webView goBack];
        [self dissMissListView];
        self.textField.text = self.webView.URL.absoluteString;
        return;
    }
    NSString *url = self.textField.text;
    self.url = url;
    if (sender != self.listView) {
        [self.listView addListObject:url];
    }
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[self urlCorrectionWithURL:url]]]];
    [self.view endEditing:YES];
    [self dissMissListView];
}

- (void)showListView
{
    if (!self.isShowList) {
        [UIView animateWithDuration:0.35 animations:^{
            CGRect listRect = self.listView.frame;
            listRect.origin.x = debug_screenW - listRect.size.width;
            self.listView.frame = listRect;
        }];
    }else{
        [UIView animateWithDuration:0.35 animations:^{
            CGRect listRect = self.listView.frame;
            listRect.origin.x = debug_screenW;
            self.listView.frame = listRect;
        }];
    }
    self.isShowList = !self.isShowList;
    
}

- (DebugH5webListView *)listView
{
    if (!_listView) {
        _listView = [[DebugH5webListView alloc] initWithFrame:CGRectMake(debug_screenW, debug_startBar_Height, debug_screenW/2, debug_screenH - debug_startBar_Height)];
        __weak typeof(self) weakself = self;
        _listView.clickUrl = ^(NSIndexPath *indexPath, NSString *url) {
            weakself.textField.text = url;
            [weakself buttonClick:weakself.listView];
        };
        _listView.dissMissBlock = ^{
            [weakself dissMissListView];
        };
    }
    return _listView;
}

- (void)dissMissListView
{
    self.isShowList = NO;
    [UIView animateWithDuration:0.35 animations:^{
        CGRect listRect = self.listView.frame;
        listRect.origin.x = debug_screenW;
        self.listView.frame = listRect;
    }];
}


/// 地址修正
- (NSString *)urlCorrectionWithURL:(NSString *)URL {
    if (!URL || URL.length <= 0) { return URL; }
    
    if (![URL hasPrefix:@"http://"] && ![URL hasPrefix:@"https://"]) {
        return [NSString stringWithFormat:@"https://%@",URL];
    }
    
    if ([URL hasPrefix:@":"]) {
        return [NSString stringWithFormat:@"https%@",URL];
    }
    
    if ([URL hasPrefix:@"//"]) {
        return [NSString stringWithFormat:@"https:%@",URL];
    }
    
    if ([URL hasPrefix:@"/"]) {
        return [NSString stringWithFormat:@"https:/%@",URL];
    }
    
    return URL;
}

#pragma mark -------delegate-------

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self buttonClick:nil];
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self dissMissListView];
}

- (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView
{
    [self dissMissListView];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self dissMissListView];
}


@end

